<template>
  <div class="row">
    <div class="col">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="ruleForm.xingming"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="QQ">
          <el-input v-model="ruleForm.qq"></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="ruleForm.birthday"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="省市">
          <el-cascader
            :options="address()"
            :props="{value:'label'}"
            v-model="selectedOptions"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { update } from "../../../plugins/api.js";
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }]
      },
      selectedOptions: []
    };
  },
  mounted() {
    this.ruleForm = JSON.parse(JSON.stringify(this.getuser));
    if (this.ruleForm.address) {
      this.selectedOptions = [
        this.ruleForm.address.province,
        this.ruleForm.address.city,
        this.ruleForm.address.area
      ];
    }
    console.log(this.ruleForm);
  },
  computed: mapGetters(["getuser"]),
  methods: {
    address() {
      const address = window.address || [];
      return address;
    },
    submitForm() {
      update(this.ruleForm)
        .then(() => {
          this.$store.dispatch("session");
          this.$message({
            type: "success",
            message: "修改成功!"
          });
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: `${err}`
          });
        });
    },
    handleChange() {
      const data = {
        province: this.selectedOptions[0],
        city: this.selectedOptions[1],
        area: this.selectedOptions[2]
      };
      this.ruleForm.address = data;
    }
  }
};
</script>

<style scoped>
.el-radio-group {
  margin-top: 9px;
}
</style>